using B.S.Databasic.Api.Read.Application.Command.Permission;
using B.S.Databasic.Domain.RBAC;
using B.S.Databasic.ErrorCode;
using B.S.Databasic.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Databasic.Api.Read.Application.Handler.Permission
{
    public class GetUserPermissionsHandler : IRequestHandler<GetUserPermissionsCommand, ApiResult<List<PermissionModel>>>
    {
        private readonly IBaseRepository<AccountRoleModel> _accountRoleRepo;
        private readonly IBaseRepository<PermissionRoleModel> _permissionRoleRepo;
        private readonly IBaseRepository<PermissionModel> _permissionRepo;
        public GetUserPermissionsHandler(
            IBaseRepository<AccountRoleModel> accountRoleRepo,
            IBaseRepository<PermissionRoleModel> permissionRoleRepo,
            IBaseRepository<PermissionModel> permissionRepo)
        {
            _accountRoleRepo = accountRoleRepo;
            _permissionRoleRepo = permissionRoleRepo;
            _permissionRepo = permissionRepo;
        }
        public async Task<ApiResult<List<PermissionModel>>> Handle(GetUserPermissionsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<PermissionModel>>();
            try
            {
                var roleIds = _accountRoleRepo.GetAll().Where(x => !x.IsDeleted && x.AccountId == request.UserId).Select(x => x.RoleId).ToList();
                if (roleIds == null || !roleIds.Any())
                {
                    res.Data = new List<PermissionModel>();
                    res.Msg = "未找到用户角色";
                    res.Code = ApiEnum.Error;
                    return await Task.FromResult(res);
                }
                var permissionIds = _permissionRoleRepo.GetAll().Where(x => !x.IsDeleted && roleIds.Contains(x.RoleId)).Select(x => x.PermissionId).Distinct().ToList();
                var permissions = _permissionRepo.GetAll().Where(x => !x.IsDeleted && permissionIds.Contains(x.Id)).OrderBy(x => x.Number).ToList();
                res.Data = permissions;
                res.Msg = "查询权限成功!";
                res.Code = ApiEnum.Success;
            }
            catch (System.Exception ex)
            {
                res.Data = null;
                res.Msg = "查询权限异常：" + ex.Message;
                res.Code = ApiEnum.Error;
            }
            return await Task.FromResult(res);
        }
    }
} 